package service

import (
	"context"

	"go.opentelemetry.io/otel"

	pb "goods/api/goods/v1"
	"goods/internal/biz"
)

func (s *GoodsService) CreateProduct(ctx context.Context, req *pb.CreateProductRequest) (*pb.CreateProductReply, error) {
	s.log.Infof("input data %v", req)
	err := s.product.Create(ctx, &biz.Product{
		Name:   req.Name,
		ProductCode: req.ProductCode,
	})
	return &pb.CreateProductReply{}, err
}

func (s *GoodsService) UpdateProduct(ctx context.Context, req *pb.UpdateProductRequest) (*pb.UpdateProductReply, error) {
	s.log.Infof("input data %v", req)
	err := s.product.Update(ctx, req.ProductId, &biz.Product{
		Name:   req.Name,
		SalePlatform: req.SalePlatform,
	})
	return &pb.UpdateProductReply{}, err
}

func (s *GoodsService) DeleteProduct(ctx context.Context, req *pb.DeleteProductRequest) (*pb.DeleteProductReply, error) {
	s.log.Infof("input data %v", req)
	err := s.product.Delete(ctx, req.ProductId)
	return &pb.DeleteProductReply{}, err
}

func (s *GoodsService) GetProduct(ctx context.Context, req *pb.GetProductRequest) (*pb.GetProductReply, error) {
	tr := otel.Tracer("api")
	ctx, span := tr.Start(ctx, "GetProduct")
	defer span.End()
	p, err := s.product.Get(ctx, req.ProductId)
	if err != nil {
		return nil, err
	}
	return &pb.GetProductReply{Product: &pb.Product{ProductId: p.ProductId, Name: p.Name, ProductCode: p.ProductCode, PColor: p.PColor, PSize: p.PSize, SalePlatform: p.SalePlatform}}, nil
}

func (s *GoodsService) ListProduct(ctx context.Context, req *pb.ListProductRequest) (*pb.ListProductReply, error) {
	ps, err := s.product.List(ctx)
	reply := &pb.ListProductReply{}
	for _, p := range ps {
		reply.Results = append(reply.Results, &pb.Product{
			ProductId:      p.ProductId,
			Name:   p.Name,
			ProductCode: p.ProductCode,
			PColor: p.PColor,
			PSize: p.PSize,
			SalePlatform: p.SalePlatform,
		})
	}
	return reply, err
}

